// 2013-7-28下午12:41:04  net.betou.trade.admin.action.AdministratorsAct.java

package net.betou.trade.admin.action;

import static net.betou.common.page.SimplePage.cpn;
import static net.betou.common.page.SimplePage.cpnPageSize;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.betou.common.page.Pagination;
import net.betou.common.util.TradeUtils;
import net.betou.common.web.RequestUtils;
import net.betou.trade.action.abs.ActionSupport;
import net.betou.trade.entity.main.AgentAndAdmins;
import net.betou.trade.entity.main.AgentAndAdminsExt;
import net.betou.trade.entity.main.Role;
import net.betou.trade.main.manager.agencyorproxy.SystemAdminMng;
import net.betou.trade.main.manager.role.SystemRoleMng;
import net.betou.trade.web.Messages;
import net.betou.trade.web.ResponseUtil;
import net.betou.trade.web.WebErrors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 系统管理员Act
 * @author 叶装装
 */
@Controller
public class AdminsAct extends ActionSupport < AgentAndAdmins >{
	
	private static final Logger log = LoggerFactory.getLogger( AdminsRoleAct.class );
	
	private static final String DIRECTORY = "admin/system";
	
	/**
	 * version 1.1
	 * @return
	 */
	@RequestMapping( "/systemadmin/v_list.jspx" )
	public String list( Integer pageSize, Integer pageNo, String filterStatus, String searchProperty, String searchValue, String orderProperty, String orderDirection, HttpServletRequest request, HttpServletResponse response, ModelMap model  ){
		
		pageSize = cpnPageSize( pageSize );
		pageNo = cpn( pageNo );
		
		Pagination pagination =  mng.getPage( searchProperty, searchValue, orderProperty, orderDirection, pageNo, pageSize, filterStatus );
		
		paramToModel( model, pagination, null, pageSize, searchProperty, searchValue, orderProperty, orderDirection, filterStatus );
		return getListPage( );
	}
	
	/**
	 * version 1.1
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping( "/systemadmin/v_add.jspx" )
	public String v_add( HttpServletRequest request, ModelMap model ){
		AgentAndAdmins admin = TradeUtils.getAdmin( request );
		// 获取系统管理员的级别设置
		model.addAttribute( "roleList",  roleMng.listToAdmin( admin ) );
		return getAddPage( );
	}
	
	@RequestMapping( "/systemadmin/o_save.jspx" )
	public String o_save( AgentAndAdmins bean, AgentAndAdminsExt ext, Integer[ ] roleIds,  HttpServletRequest request, HttpServletResponse response, ModelMap model ){
		
		WebErrors errors = validateSave( bean, roleIds );
		
		if( errors.hasErrors( ) ){
			return errors.showErrorPage( model );
		}
		
		String ip = RequestUtils.getIpAddr( request );
		bean = mng.save( ip, roleIds, bean, ext );
		logMng.operating( 0, request, Messages.LOG_SYSTEM_ADMIN, "id=" + bean.getId( ) + ",username=" + bean.getUsername( ));
		
		return "redirect:v_list.jspx";
	}
	
	@RequestMapping ( "/systemadmin/v_edit.jspx" )
	public String v_edit( Integer id, HttpServletRequest request, ModelMap model ){

		WebErrors errors = validateUpdate( request, id );
		
		if( errors.hasErrors( ) ){
			return errors.showErrorPage( model );
		}
		
		AgentAndAdmins bean = mng.findById( id );
		
		model.addAttribute( "bean", bean );
		AgentAndAdmins admin = TradeUtils.getAdmin( request );
		
		model.addAttribute( "roleList",  roleMng.listToAdmin( admin ) );
		
		return getUpdatePage( );
	}
	
	@RequestMapping ( "/systemadmin/o_update.jspx" )
	public String o_update( Boolean disabled,  Integer id, String password,  String email,  Integer[ ] roleIds, AgentAndAdminsExt ext, HttpServletRequest request, ModelMap model ){
		
		WebErrors errors = validateUpdate( request, id );
		
		if( errors.hasErrors( ) ){
			return errors.showErrorPage( model );
		}
		
		AgentAndAdmins bean = mng.findById( id );
		
		bean = mng.update( disabled, password, email, bean, ext, roleIds );
		logMng.operating( 1, request, Messages.LOG_SYSTEM_ADMIN, "id=" + bean.getId( ) + ",username=" + bean.getUsername( ));
		
		return "redirect:v_list.jspx";
	}
	
	@RequestMapping( "/systemadmin/o_delete.jspx" )
	public void o_delete( Integer [ ] ids, HttpServletResponse response, HttpServletRequest request ){
		
		ResponseUtil util = validateDelete( ids, response, request );

		if( util.hasResponse( ) ){
			util.renderJson( );
			return;
		}

//		Role[] roles = roleMng.findListByAdminIds( ids );//暂时先不删除创建的角色
		
		AgentAndAdmins [ ] beans = mng.deleteByIds( ids );
		
//		if(roles.length>0){//暂时先不删除创建的角色
//			Integer[] roleIds = buildIdArray(roles);
//			roleMng.deleteByIds(roleIds);
//		}

		for ( AgentAndAdmins bean : beans ){
			log.info( "delete Admin id={}", bean.getId( ) );
			
			logMng.operating( 2, request, Messages.LOG_SYSTEM_ADMIN, "id=" + bean.getId( ) + ",username=" + bean.getUsername( ));
		}

		util.addSuccessResponse( Messages.getDeleteSuccessMessage( beans.length ) );

		util.renderJson( );
		return;
		
	}
	
	private Integer[] buildIdArray(Role[] roles){
		Integer[] is = new Integer[roles.length];
		for(int i=0; i<roles.length; i++){
			is[i] = roles[i].getId();
		}
		return is;
	}
	
	
	private ResponseUtil validateDelete( Integer [ ] ids, HttpServletResponse response, HttpServletRequest request ) {
		ResponseUtil util = ResponseUtil.create( response );

		if( ids == null || ids.length == 0 ){
			util.addErrorResponse( Messages.DATA_NOT_SELECT );
			return util;
		}
		for ( Integer id : ids ){
			AgentAndAdmins admin = mng.findById( id );
			if( admin == null ){
				util.addErrorResponse( Messages.getNotExistMessage( id ) ); // 只要有一个数据不存在就提示不可删除
				break;
			}
		}
		return util;
	}
	
	
	
	/**
	 * version 1.1
	 * @param request
	 * @param id
	 * @return
	 */
	private WebErrors validateUpdate( HttpServletRequest request, Integer id ){
		WebErrors errors = WebErrors.create( );
		
		if( id == null || id == 0 ){
			errors.addError( Messages.DATA_NOT_EXIST );
			return errors;
		}
		
		AgentAndAdmins admin = mng.findBySystem( id );
		
		if( admin == null ){
			errors.addError( Messages.DATA_NOT_EXIST );
			return errors;
		}
		
		return errors;
			
	}
	
	private WebErrors validateSave( AgentAndAdmins bean, Integer [ ] roleIds ){
		WebErrors errors = WebErrors.create( );
		
		return errors;
	}
	
	
	@Autowired
	private SystemAdminMng mng;
	
	@Autowired
	private SystemRoleMng roleMng;


	@Override
	protected String getDirectory( ) {
		return DIRECTORY;
	}
}
